<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ollama Chat</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.7.0/styles/github.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.7.0/lib/highlight.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked@4.2.12/marked.min.js"></script>
    <style>
        :root {
            --primary-color: #4F46E5;
            --primary-hover: #4338CA;
            --bg-color: #F9FAFB;
            --card-bg: #FFFFFF;
            --text-primary: #111827;
            --text-secondary: #6B7280;
            --border-color: #E5E7EB;
        }

        body {
            background-color: var(--bg-color);
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            color: var(--text-primary);
            line-height: 1.5;
        }

        .app-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
            display: flex;
            gap: 20px;
            height: calc(100vh - 40px);
        }

        .sidebar {
            width: 300px;
            background-color: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .sidebar-header {
            margin-bottom: 24px;
        }

        .sidebar-header h2 {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--text-primary);
            margin: 0;
        }

        .service-info {
            background-color: var(--bg-color);
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 20px;
        }

        .service-info h4 {
            font-size: 1rem;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 12px;
        }

        .info-item {
            position: relative;
            margin-bottom: 12px;
        }

        .info-label {
            font-size: 0.875rem;
            font-weight: 500;
            color: var(--text-secondary);
            margin-bottom: 4px;
        }

        .info-value-container {
            position: relative;
            display: flex;
            align-items: center;
        }

        .info-value {
            flex: 1;
            padding-right: 32px;
            word-break: break-all;
            min-height: 36px;
            display: flex;
            align-items: center;
        }

        .chat-container {
            flex: 1;
            background-color: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
            background-color: var(--card-bg);
        }

        .chat-header h3 {
            font-size: 1.25rem;
            font-weight: 600;
            margin: 0;
            color: var(--text-primary);
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background-color: var(--bg-color);
        }

        .message {
            margin-bottom: 16px;
            max-width: 80%;
            animation: fadeIn 0.3s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .user-message {
            margin-left: auto;
            background-color: var(--primary-color);
            color: white;
            border-radius: 12px 12px 0 12px;
            padding: 12px 16px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .assistant-message {
            margin-right: auto;
            background-color: var(--card-bg);
            color: var(--text-primary);
            border-radius: 12px 12px 12px 0;
            padding: 12px 16px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .thinking-message {
            margin-right: auto;
            background-color: var(--bg-color);
            color: var(--text-secondary);
            border-radius: 12px 12px 12px 0;
            padding: 12px 16px;
            font-style: italic;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .chat-input {
            padding: 20px;
            border-top: 1px solid var(--border-color);
            background-color: var(--card-bg);
            display: flex;
            gap: 12px;
        }

        .chat-input input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.2s;
        }

        .chat-input input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        .chat-input button {
            padding: 12px 24px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: background-color 0.2s;
        }

        .chat-input button:hover {
            background-color: var(--primary-hover);
        }

        .markdown-content {
            line-height: 1.6;
        }

        .markdown-content pre {
            background-color: var(--bg-color);
            padding: 16px;
            border-radius: 8px;
            overflow-x: auto;
            margin: 12px 0;
        }

        .markdown-content code {
            background-color: var(--bg-color);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Fira Code', monospace;
            font-size: 0.9em;
        }

        .markdown-content p {
            margin-bottom: 1em;
        }

        .markdown-content ul, .markdown-content ol {
            margin-bottom: 1em;
            padding-left: 2em;
        }

        .markdown-content h1, .markdown-content h2, .markdown-content h3 {
            margin-top: 1.5em;
            margin-bottom: 0.5em;
            font-weight: 600;
        }

        .markdown-content blockquote {
            border-left: 4px solid var(--border-color);
            padding-left: 1em;
            margin-left: 0;
            color: var(--text-secondary);
        }

        /* Scrollbar styling */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--bg-color);
        }

        ::-webkit-scrollbar-thumb {
            background: var(--border-color);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--text-secondary);
        }

        .chat-list {
            flex: 1;
            overflow-y: auto;
            margin-top: 20px;
        }

        .chat-item {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: background-color 0.2s;
            display: flex;
            align-items: center;
            gap: 8px;
            position: relative;
        }

        .chat-item:hover {
            background-color: var(--bg-color);
        }

        .chat-item.active {
            background-color: var(--primary-color);
            color: white;
        }

        .chat-item .title {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 0.9rem;
        }

        .chat-item .delete-btn {
            display: none;
            padding: 4px 8px;
            background: none;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.2s;
        }

        .chat-item:hover .delete-btn {
            display: block;
        }

        .chat-item .delete-btn:hover {
            color: #EF4444;
            background-color: rgba(239, 68, 68, 0.1);
        }

        .new-chat-button {
            padding: 12px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: background-color 0.2s;
        }

        .new-chat-button:hover {
            background-color: var(--primary-hover);
        }

        .new-chat-button svg {
            width: 16px;
            height: 16px;
        }

        .thinking-content {
            color: var(--text-secondary);
            font-style: italic;
            padding: 8px 12px;
            background-color: var(--bg-color);
            border-radius: 8px;
            margin-bottom: 8px;
        }
        
        .thinking-separator {
            border: none;
            border-top: 1px solid var(--border-color);
            margin: 8px 0;
        }
        
        .assistant-content {
            padding: 8px 12px;
        }

        .chat-section {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: var(--bg-color);
            border-radius: 8px;
            padding: 16px;
            overflow: hidden;
        }

        .chat-section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }

        .chat-section-header h4 {
            font-size: 1rem;
            font-weight: 600;
            color: var(--text-primary);
            margin: 0;
        }

        .chat-list {
            flex: 1;
            overflow-y: auto;
            margin: 0;
            padding-right: 8px;
        }

        .chat-list::-webkit-scrollbar {
            width: 6px;
        }

        .chat-list::-webkit-scrollbar-track {
            background: transparent;
        }

        .chat-list::-webkit-scrollbar-thumb {
            background: var(--border-color);
            border-radius: 3px;
        }

        .chat-list::-webkit-scrollbar-thumb:hover {
            background: var(--text-secondary);
        }

        .chat-item {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 8px;
            position: relative;
            background-color: var(--card-bg);
        }

        .chat-item:hover {
            background-color: var(--primary-color);
            color: white;
        }

        .chat-item:hover .delete-btn {
            color: white;
        }

        .chat-item.active {
            background-color: var(--primary-color);
            color: white;
        }

        .chat-item .title {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 0.9rem;
        }

        .chat-item .delete-btn {
            display: none;
            padding: 4px 8px;
            background: none;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.2s;
        }

        .chat-item:hover .delete-btn {
            display: block;
        }

        .chat-item .delete-btn:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .config-panel {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            width: 400px;
            z-index: 1000;
        }

        .config-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
        }

        .config-header h4 {
            margin: 0;
            font-size: 1.1rem;
            font-weight: 600;
        }

        .close-button {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: var(--text-secondary);
        }

        .config-content {
            padding: 20px;
        }

        .config-item {
            margin-bottom: 16px;
        }

        .config-item label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-primary);
        }

        .config-item input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            font-size: 0.9rem;
        }

        .config-actions {
            display: flex;
            gap: 12px;
            margin-top: 24px;
        }

        .test-button, .save-button {
            flex: 1;
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.2s;
        }

        .test-button {
            background-color: var(--bg-color);
            color: var(--text-primary);
        }

        .save-button {
            background-color: var(--primary-color);
            color: white;
        }

        .test-button:hover {
            background-color: var(--border-color);
        }

        .save-button:hover {
            background-color: var(--primary-hover);
        }

        .config-button {
            width: 100%;
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.2s;
        }

        .config-button:hover {
            background-color: var(--primary-hover);
        }

        .toggle-token {
            position: absolute;
            right: 8px;
            background: none;
            border: none;
            padding: 4px;
            cursor: pointer;
            color: var(--text-secondary);
            transition: color 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .toggle-token:hover {
            color: var(--text-primary);
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>Ollama Chat</h2>
            </div>
            <button class="new-chat-button" onclick="newChat()">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M12 5v14M5 12h14"/>
                </svg>
                New Chat
            </button>
            <div class="service-info">
                <h4>Service Information</h4>
                <div class="info-item">
                    <div class="info-label">API Endpoint</div>
                    <div class="info-value" id="apiEndpoint">{{ api_endpoint }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Model</div>
                    <div class="info-value" id="modelName">{{ model }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Token</div>
                    <div class="info-value-container">
                        <div class="info-value" id="apiToken" style="font-family: monospace;" data-token="{{ token }}">
                            {% if token %}
                            ••••••••••••••••
                            {% else %}
                            <span style="color: #EF4444;">Not configured</span>
                            {% endif %}
                        </div>
                        {% if token %}
                        <button class="toggle-token" onclick="toggleToken()" type="button">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                                <circle cx="12" cy="12" r="3"/>
                            </svg>
                        </button>
                        {% endif %}
                    </div>
                </div>
                <div class="info-item">
                    <button class="config-button" onclick="showConfigPanel()">Configure</button>
                </div>
                {% if show_config_prompt %}
                <div class="info-item" style="margin-top: 16px; padding: 12px; background-color: #FEF2F2; border-radius: 8px; border: 1px solid #FECACA;">
                    <div style="color: #DC2626; font-size: 0.875rem; display: flex; align-items: center; gap: 8px;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10"/>
                            <line x1="12" y1="8" x2="12" y2="12"/>
                            <line x1="12" y1="16" x2="12.01" y2="16"/>
                        </svg>
                        Please configure your API token to start chatting
                    </div>
                </div>
                {% endif %}
            </div>
            <div class="chat-section">
                <div class="chat-section-header">
                    <h4>Chat History</h4>
                </div>
                <div class="chat-list" id="chatList">
                    {% for chat in chats %}
                    <div class="chat-item {% if chat.id == current_chat_id %}active{% endif %}" 
                         onclick="switchChat('{{ chat.id }}')">
                        <div class="title">{{ chat.title }}</div>
                        <button class="delete-btn" onclick="deleteChat('{{ chat.id }}', event)">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2M10 11v6M14 11v6"/>
                            </svg>
                        </button>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        <div class="chat-container">
            <div class="chat-header">
                <h3>Chat</h3>
            </div>
            <div class="chat-messages" id="chatMessages">
                <!-- Messages will be added here -->
            </div>
            <div class="chat-input">
                <input type="text" id="messageInput" placeholder="Type your message..." autocomplete="off">
                <button onclick="sendMessage()">Send</button>
            </div>
        </div>
    </div>

    <!-- 添加配置面板 -->
    <div id="configPanel" class="config-panel" style="display: none;">
        <div class="config-header">
            <h4>Configuration</h4>
            <button class="close-button" onclick="hideConfigPanel()">×</button>
        </div>
        <div class="config-content">
            <div class="config-item">
                <label for="configApiUrl">API Endpoint</label>
                <input type="text" id="configApiUrl" placeholder="http://localhost:11434">
            </div>
            <div class="config-item">
                <label for="configToken">Token</label>
                <input type="password" id="configToken" placeholder="Enter your token">
            </div>
            <div class="config-item">
                <label for="configModel">Model</label>
                <input type="text" id="configModel" placeholder="llama2">
            </div>
            <div class="config-actions">
                <button class="test-button" onclick="testConnection()">Test Connection</button>
                <button class="save-button" onclick="saveConfig()">Save</button>
            </div>
        </div>
    </div>

    <script>
        // Initialize variables
        const chatState = {
            currentChatId: '{{ current_chat_id }}',
            messages: [],
            isProcessing: false
        };

        // Token 显示/隐藏功能
        let tokenVisible = false;

        // Initialize highlight.js
        hljs.highlightAll();

        // Configure marked to use highlight.js for code blocks
        marked.setOptions({
            highlight: function(code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    try {
                        return hljs.highlight(code, { language: lang }).value;
                    } catch (e) {
                        console.error(e);
                    }
                }
                try {
                    return hljs.highlightAuto(code).value;
                } catch (e) {
                    console.error(e);
                    return code;
                }
            },
            breaks: true
        });

        function toggleToken() {
            const tokenElement = document.getElementById('apiToken');
            const toggleButton = document.querySelector('.toggle-token');
            const actualToken = tokenElement.getAttribute('data-token');
            
            console.log('Token visibility:', tokenVisible);
            console.log('Actual token:', actualToken);
            
            tokenVisible = !tokenVisible;
            if (tokenVisible) {
                // 显示实际 token
                tokenElement.textContent = actualToken;
                toggleButton.innerHTML = `
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/>
                        <line x1="1" y1="1" x2="23" y2="23"/>
                    </svg>
                `;
            } else {
                // 显示隐藏的 token
                tokenElement.textContent = '••••••••••••••••';
                toggleButton.innerHTML = `
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                        <circle cx="12" cy="12" r="3"/>
                    </svg>
                `;
            }
        }

        // 初始化时设置正确的图标和 token 状态
        document.addEventListener('DOMContentLoaded', function() {
            const tokenElement = document.getElementById('apiToken');
            const toggleButton = document.querySelector('.toggle-token');
            
            // 确保初始状态是隐藏的
            tokenVisible = false;
            tokenElement.textContent = '••••••••••••••••';
            toggleButton.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                    <circle cx="12" cy="12" r="3"/>
                </svg>
            `;
        });

        // UI Functions
        function addMessage(content, isUser = false, isThinking = false) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : isThinking ? 'thinking-message' : 'assistant-message'}`;
            
            if (isThinking) {
                messageDiv.textContent = content;
            } else {
                // 检查是否包含思考内容
                const thinkMatch = content.match(/<think>(.*?)<\/think>/s);
                if (thinkMatch) {
                    // 创建思考内容容器
                    const thinkingDiv = document.createElement('div');
                    thinkingDiv.className = 'thinking-content';
                    thinkingDiv.textContent = thinkMatch[1].trim();
                    messageDiv.appendChild(thinkingDiv);
                    
                    // 创建分隔线
                    const separator = document.createElement('hr');
                    separator.className = 'thinking-separator';
                    messageDiv.appendChild(separator);
                    
                    // 创建实际内容容器
                    const contentDiv = document.createElement('div');
                    contentDiv.className = 'assistant-content';
                    contentDiv.innerHTML = marked.parse(content.replace(/<think>.*?<\/think>/s, '').trim());
                    messageDiv.appendChild(contentDiv);
                } else {
                    messageDiv.innerHTML = `<div class="markdown-content">${marked.parse(content)}</div>`;
                }
            }
            
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function clearMessages() {
            document.getElementById('chatMessages').innerHTML = '';
        }

        function setLoadingState(isLoading) {
            const chatItems = document.querySelectorAll('.chat-item');
            chatItems.forEach(item => item.style.opacity = isLoading ? '0.5' : '1');
        }

        // Chat Management Functions
        function loadChatHistory() {
            fetch(`/api/chats/${chatState.currentChatId}`)
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(data => {
                            throw new Error(data.message || 'Failed to load chat history');
                        });
                    }
                    return response.json();
                })
                .then(messages => {
                    clearMessages();
                    messages.forEach(msg => {
                        addMessage(msg.content, msg.role === 'user');
                    });
                })
                .catch(error => {
                    console.error('Error loading chat history:', error);
                    if (error.status === 404) {
                        clearMessages();
                    } else {
                        clearMessages();
                        addMessage(`Error: ${error.message}`, false);
                    }
                });
        }

        function newChat() {
            if (chatState.isProcessing) return;
            chatState.isProcessing = true;

            const newChatButton = document.querySelector('.new-chat-button');
            const originalText = newChatButton.innerHTML;
            newChatButton.innerHTML = 'Creating...';
            newChatButton.disabled = true;

            fetch('/api/chats/new', { 
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(data => {
                        throw new Error(data.message || 'Failed to create new chat');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'success') {
                    chatState.currentChatId = data.chat_id;
                    clearMessages();
                    updateChatList();
                    addMessage('Hello! How can I help you today?', false);
                } else {
                    throw new Error(data.message || 'Failed to create new chat');
                }
            })
            .catch(error => {
                console.error('Error creating new chat:', error);
                clearMessages();
                addMessage(`Error: ${error.message}`, false);
            })
            .finally(() => {
                newChatButton.innerHTML = originalText;
                newChatButton.disabled = false;
                chatState.isProcessing = false;
            });
        }

        function switchChat(chatId) {
            if (chatState.isProcessing) return;
            chatState.isProcessing = true;

            setLoadingState(true);
            
            fetch(`/api/chats/${chatId}/switch`, { 
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(data => {
                        throw new Error(data.message || 'Failed to switch chat');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'success') {
                    chatState.currentChatId = chatId;
                    loadChatHistory();
                    updateChatList();
                } else {
                    throw new Error(data.message || 'Failed to switch chat');
                }
            })
            .catch(error => {
                console.error('Error switching chat:', error);
                clearMessages();
                addMessage(`Error: ${error.message}`, false);
            })
            .finally(() => {
                setLoadingState(false);
                chatState.isProcessing = false;
            });
        }

        function updateChatList() {
            fetch('/api/chats')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Failed to fetch chat list');
                    }
                    return response.json();
                })
                .then(chats => {
                    const chatList = document.getElementById('chatList');
                    if (chats && chats.length > 0) {
                        chatList.innerHTML = chats.map(chat => `
                            <div class="chat-item ${chat.id === chatState.currentChatId ? 'active' : ''}" 
                                 onclick="switchChat('${chat.id}')">
                                <div class="title">${chat.title}</div>
                                <button class="delete-btn" onclick="deleteChat('${chat.id}', event)">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2M10 11v6M14 11v6"/>
                                    </svg>
                                </button>
                            </div>
                        `).join('');
                    } else {
                        chatList.innerHTML = '<div class="chat-item" style="color: var(--text-secondary); text-align: center;">No chats yet</div>';
                    }
                })
                .catch(error => {
                    console.error('Error updating chat list:', error);
                    const chatList = document.getElementById('chatList');
                    chatList.innerHTML = '<div class="chat-item" style="color: var(--text-secondary); text-align: center;">Error loading chat list</div>';
                });
        }

        function deleteChat(chatId, event) {
            // 阻止事件冒泡，避免触发父元素的点击事件
            event.stopPropagation();
            
            if (chatState.isProcessing) return;
            chatState.isProcessing = true;

            // 显示加载状态
            const deleteBtn = event.currentTarget;
            const originalHTML = deleteBtn.innerHTML;
            deleteBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg>';
            deleteBtn.style.pointerEvents = 'none';

            if (confirm('Are you sure you want to delete this chat?')) {
                fetch(`/api/chats/${chatId}/delete`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(data => {
                            throw new Error(data.message || 'Failed to delete chat');
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.status === 'success') {
                        // 如果删除的是当前对话，切换到新对话
                        if (chatId === chatState.currentChatId) {
                            newChat();
                        } else {
                            updateChatList();
                        }
                    } else {
                        throw new Error(data.message || 'Failed to delete chat');
                    }
                })
                .catch(error => {
                    console.error('Error deleting chat:', error);
                    alert(`Error: ${error.message}`);
                })
                .finally(() => {
                    // 恢复按钮状态
                    deleteBtn.innerHTML = originalHTML;
                    deleteBtn.style.pointerEvents = 'auto';
                    chatState.isProcessing = false;
                });
            } else {
                // 用户取消删除，恢复按钮状态
                deleteBtn.innerHTML = originalHTML;
                deleteBtn.style.pointerEvents = 'auto';
                chatState.isProcessing = false;
            }
        }

        function sendMessage() {
            if (chatState.isProcessing) return;
            chatState.isProcessing = true;

            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (message) {
                addMessage(message, true);
                input.value = '';
                
                const thinkingDiv = document.createElement('div');
                thinkingDiv.className = 'message thinking-message';
                thinkingDiv.textContent = 'Thinking...';
                document.getElementById('chatMessages').appendChild(thinkingDiv);
                
                fetch('/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ message })
                })
                .then(response => response.json())
                .then(data => {
                    const chatMessages = document.getElementById('chatMessages');
                    chatMessages.removeChild(chatMessages.lastChild);
                    
                    if (data.error) {
                        if (data.error === 'Please configure your API token first') {
                            showConfigPanel();
                        }
                        addMessage(`Error: ${data.error}`);
                    } else {
                        addMessage(data.response);
                        updateChatList();
                    }
                })
                .catch(error => {
                    const chatMessages = document.getElementById('chatMessages');
                    chatMessages.removeChild(chatMessages.lastChild);
                    addMessage(`Error: ${error.message}`);
                })
                .finally(() => {
                    chatState.isProcessing = false;
                });
            }
        }

        // Initialize chat
        document.addEventListener('DOMContentLoaded', function() {
            loadChatHistory();
            updateChatList();

            // Allow sending message with Enter key
            document.getElementById('messageInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    sendMessage();
                }
            });
        });

        // 配置管理函数
        function showConfigPanel() {
            const panel = document.getElementById('configPanel');
            panel.style.display = 'block';
            
            // 加载当前配置
            fetch('/api/config')
                .then(response => response.json())
                .then(config => {
                    document.getElementById('configApiUrl').value = config.api_url;
                    document.getElementById('configToken').value = config.token;
                    document.getElementById('configModel').value = config.model;
                })
                .catch(error => {
                    console.error('Error loading config:', error);
                });
        }

        function hideConfigPanel() {
            document.getElementById('configPanel').style.display = 'none';
        }

        function testConnection() {
            const apiUrl = document.getElementById('configApiUrl').value;
            const token = document.getElementById('configToken').value;
            
            fetch('/api/config/test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    api_url: apiUrl,
                    token: token
                })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
            })
            .catch(error => {
                console.error('Error testing connection:', error);
                alert('Connection test failed');
            });
        }

        // 更新保存配置时的 token 显示
        function saveConfig() {
            const apiUrl = document.getElementById('configApiUrl').value;
            const token = document.getElementById('configToken').value;
            const model = document.getElementById('configModel').value;
            
            fetch('/api/config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    api_url: apiUrl,
                    token: token,
                    model: model
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 更新显示
                    document.getElementById('apiEndpoint').textContent = apiUrl;
                    document.getElementById('modelName').textContent = model;
                    
                    // 更新 token 显示
                    const tokenElement = document.getElementById('apiToken');
                    tokenElement.setAttribute('data-token', token);
                    if (!tokenVisible) {
                        tokenElement.textContent = '••••••••••••••••';
                    } else {
                        tokenElement.textContent = token;
                    }
                    
                    // 如果之前没有 token，添加切换按钮
                    if (!tokenElement.querySelector('.toggle-token')) {
                        const toggleButton = document.createElement('button');
                        toggleButton.className = 'toggle-token';
                        toggleButton.onclick = toggleToken;
                        toggleButton.type = 'button';
                        toggleButton.innerHTML = `
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                                <circle cx="12" cy="12" r="3"/>
                            </svg>
                        `;
                        tokenElement.parentElement.appendChild(toggleButton);
                    }
                    
                    // 隐藏配置提示（如果有）
                    const configPrompt = document.querySelector('.info-item[style*="background-color: #FEF2F2"]');
                    if (configPrompt) {
                        configPrompt.remove();
                    }
                    
                    hideConfigPanel();
                    alert('Configuration saved successfully');
                } else {
                    alert(data.message || 'Failed to save configuration');
                }
            })
            .catch(error => {
                console.error('Error saving config:', error);
                alert('Failed to save configuration');
            });
        }
    </script>
</body>
</html> 